package com.todofun.common.app;

import java.util.Properties;
import java.util.TimerTask;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.todofun.common.app.ConfigUtil;

public class MailTools  {
	
	protected static final Log logger = LogFactory.getLog(MailTools.class);
	
	public void sendMail(String subject,String context,String targetMail) {
		
		String mailSwitch=this.getConfigUtil().getProperty("mailSwitch");
		
		if(mailSwitch.equals("open")){
		try {
			final Properties props = new Properties();
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.auth", "true");

			String sourceMail = this.getConfigUtil().getProperty("sourceMail");
			String sourceMailSmtp = this.getConfigUtil().getProperty("sourceMailSmtp");
			String sourceMailUser = this.getConfigUtil().getProperty("sourceMailUser");
			String sourceMailPassword = this.getConfigUtil().getProperty("sourceMailPassword");
			
			Session myMailSession = Session.getInstance(props);
			myMailSession.setDebug(true); // 打开DEBUG模式
			Message msg = new MimeMessage(myMailSession);
			
			msg.setFrom(new InternetAddress(sourceMail));
			
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(targetMail));
			
			msg.setContent("邮件", "text/plain");
			msg.setSentDate(new java.util.Date());
			
			msg.setSubject("[5iitt邮件]"+subject);
			
			msg.setText(context+"\n");
			
			javax.mail.Transport myTransport = myMailSession.getTransport("smtp");
			
			myTransport.connect(sourceMailSmtp, sourceMailUser, sourceMailPassword);
			
			myTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
			myTransport.close();
		} catch (Exception error) {
			//System.out.println("邮件发送失败： " + error);
			logger.debug("邮件发送失败： " + error);
		}
		}
	}
	
	/**
	 * 获得服务器地址的配置文件
	 * */
	private ConfigUtil  getConfigUtil(){
		ConfigUtil utilconfig=null;
		if(utilconfig==null){
			utilconfig=new ConfigUtil();
		}
		return utilconfig;
	}
	
	public static void main(String[] args) 
	{
		MailTools tool = new MailTools();
		tool.sendMail("test","test","wg@cic.tsinghua.edu.cn");
		System.out.print("test");
	}
}
